/*
 * @Author: 欧小兵
 * @Date: 2021-12-15 14:07:56
 * @LastEditors: 詹真琦(legendryztachi@gmail.com)
 * @LastEditTime: 2022-05-19 10:48:11
 * @FilePath: \code\cwp-front\pc-collaboration\src\handles\common\err-handle.js
 * @Description:
 */

import { APPLICATIONCATEGORYE } from '@/utils/const';
import globalMethods from "@/plugins/methods";
import {fireEvent} from "@/handles/common/sdk";
import {useBaseInfoWithOut} from "@/store/modules/base-info";

const useBaseInfo = useBaseInfoWithOut();
export default function resultHandle(result, handle, handleError=()=>{}) {
    let { app, data } = result;
    //失败回调包装，还原表单校验规则确认结果
    let handleErrorWrap = () => {
        useBaseInfo.needCheckRule = true;
        handleError.call(this, arguments);
    }
    switch (app) {
        case APPLICATIONCATEGORYE.WORKFLOW:
            //工作流只返回数据
            workflowModule.handlerWorkflow(data[app].data, handle);
            break;
        case APPLICATIONCATEGORYE.CAP4_FROM:
            _getZWIframe().csdk.core.handleSaveFormResult({
                data: {
                    ...data[app],
                    data: {
                        ...data[app].data,
                        isCwp: true,
                        ...data[app].extend && {
                            extend: data[app].extend
                        },
                    },
                },
                handle,
                handleError,
            });
            //阅读代码发现需要在这里执行。然后有需要放在下一轮宏任务执行
            setTimeout(function () {
                _getZWIframe().csdk._.runMiddleware('customRespond', data[app]);
            });
            break;
        case APPLICATIONCATEGORYE.THIRD_PARTY:
            // eslint-disable-next-line no-case-declarations
            const {data: hookData} = data[app]
            console.log(hookData);
            //执行统计,防止前端无hook，后端有hook一直循环
            // eslint-disable-next-line no-case-declarations,no-unused-vars
            let hookRunCount = 0;
            // 使用 Object.defineProperties 来劫持和记录对象访问
            abductProperties(hookData, () => ++hookRunCount);
            fireEvent('thirdPartyHandle',  {
                data:hookData,
                isCwp: true,
                thirdPartyContext: useBaseInfo.thirdPartyContext,
                success: (args) => {
                    //没有hook执行，防止循环请求
                    if (hookRunCount === 0) {
                        globalMethods.error({
                            content: "thirdPartyListener 无前端bind实现"
                        })
                        handleErrorWrap.call(this, args);
                        return;
                    }
                    handle.call(this, args);
                },
                error: handleErrorWrap,
            })
            break;
        default:
            // eslint-disable-next-line no-case-declarations
            const {code, data: resData} = data[app]
            if (code == 500 || (resData && resData?.alertMessage)) {
                const {alertMessage, weakBlock} = resData;
                if (weakBlock===true){
                    resData.workflowEvent = true;
                    globalMethods.confirm({
                        title: globalMethods.i18n('common.system.hint.label'),
                        content: globalMethods.i18n(alertMessage),
                        onOk: () => handle.call(this, resData),
                        onCancel: () => handleError(),
                    });
                }else {
                    globalMethods.warning({
                        title: globalMethods.i18n('common.system.hint.label'),
                        content: globalMethods.i18n(alertMessage),
                    }); 
                }
                
            }
    }
}

/**
 * 给obj对象加上访问记录，处理事件触发后，没有对应的bind直接执行了success,出现循环请求报错
 * */
function abductProperties(obj,log){
    const defineAccessLoggedProperty = (obj, prop) => {
        let value = obj[prop];
        Object.defineProperty(obj, prop, {
            get() {
                log();
                return value;
            },
            set(newValue) {
                log();
                value = newValue;
            },
            enumerable: true,
            configurable: true
        });
    };
    for (const prop of Object.keys(obj)) {
        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
            defineAccessLoggedProperty(obj, prop);
        }
    }
}
